package com.twp.auth.service.user;

import com.twp.auth.domain.authority.Menu;
import com.twp.auth.domain.authority.Role;
import com.twp.auth.domain.authority.user.ManageUser;
import com.twp.auth.repository.auth.RoleRepository;
import com.twp.auth.repository.user.ManageUserRepository;
import com.twp.auth.rest.api.manage.ManageUserController;
import com.twp.auth.tuple.UserRoleActionBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class ManageUserService {

    @PersistenceContext
    EntityManager entityManager;

    @Autowired
    ManageUserRepository manageUserRepository;

    @Autowired
    RoleRepository roleRepository;

    public ManageUser findAllByUserName(String userName){
        return manageUserRepository.findAllByUserNameAndStatus(userName,1);
    }

    /*
    根据条件查找用户
     */
    public Page<ManageUser> find(ManageUserController.FindBody findBody, Pageable pageable){
        return  manageUserRepository.findAll(
                (root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if(!StringUtils.isEmpty(findBody.getName())){
                        predicates.add(criteriaBuilder.like(root.get("name"), "%"+findBody.getName()+"%"));
                    }
                    if(!StringUtils.isEmpty(findBody.getUserName())){
                        predicates.add(criteriaBuilder.like(root.get("userName"), "%"+findBody.getUserName()+"%"));
                    }
                    if(!StringUtils.isEmpty(findBody.getPhoneNumber())){
                        predicates.add(criteriaBuilder.like(
                                root.join("detail", JoinType.INNER).get("phoneNumber"),
                                 "%"+findBody.getPhoneNumber()+"%"));
                    }
                    return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
                },
                pageable);
    }

    /*
    根据条件修改用户信息
     */
    public void saveOrUpdate(ManageUser manageUser){
        Date d = new Date();
        if (manageUser.getDetail()==null){
            if (manageUser.getId()!=null){
                ManageUser manageUserOld = manageUserRepository.findOne(manageUser.getId());
                if (manageUserOld!=null){
                    manageUser.setDetail(manageUserOld.getDetail());
                }
            }
        }else {
            manageUser.getDetail().setUpdateTime(d);
            manageUser.getDetail().setCreateTime(d);
        }
        if (manageUser.getCreateTime()==null){
            manageUser.setCreateTime(d);
        }
        manageUser.setUpdateTime(d);

        Optional.ofNullable(manageUser.getDetail())
                .ifPresent(
                        userDetail -> userDetail.setManageUser(manageUser)
                );

        entityManager.merge(manageUser);
    }

    /*
    根据id做用户信息的delete
     */
    public void deleteById(Integer id){
        manageUserRepository.delete(id);
    }

    public void action(UserRoleActionBody actionBody){
        ManageUser user = manageUserRepository.findOne(actionBody.getUserId());
        if (user!=null){
            List<Role> roleList = roleRepository.findAll(actionBody.getRoleIds());
            user.setRoleList(roleList);
            if (!roleList.isEmpty()){
                roleList.stream().forEach(
                        role->role.getManageUserList().add(user)
                );
                // roleRepository.save(roleList);
            }
            manageUserRepository.save(user);
           // entityManager.merge(user);
        }
    }


}
